/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainForm.java
 *
 * Created on 05.07.2010, 17:37:06
 */
package ru.ibrae.mchs.radiation.GUI;

import ru.ibrae.mchs.radiation.common.Naming;
import ru.ibrae.mchs.radiation.common.PokazatelMap;
import ru.ibrae.mchs.radiation.entities.CrossZon;
import ru.ibrae.mchs.radiation.entities.GSPos;
import ru.ibrae.mchs.radiation.entities.Geoobject;
import ru.ibrae.mchs.radiation.entities.Rajon;
import ru.ibrae.mchs.radiation.entities.SubjectRf;
import ru.ibrae.mchs.radiation.entities.controllers.DicTimeJpaController;
import ru.ibrae.mchs.radiation.entities.controllers.DicZonJpaController;
import ru.ibrae.mchs.radiation.entities.controllers.GeoobjectJpaController;
import ru.ibrae.mchs.radiation.entities.controllers.PokazatelJpaController;
import ru.ibrae.mchs.radiation.entities.controllers.ResultJpaController;
import ru.ibrae.mchs.radiation.entities.controllers.SubjectRfJpaController;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.table.TableColumnExt;
import ru.ibrae.mchs.radiation.common.Settings;
import ru.ibrae.mchs.radiation.entities.RajonOld;
import ru.ibrae.mchs.radiation.entities.Selsovet;

/**
 *
 * @author murr
 */
public final class MainForm extends javax.swing.JFrame {

    private Naming naming = Naming.NEW;

    public MainForm(File file) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        preloadPokazatelMaps(file);
        SubjectRfJpaController controller = new SubjectRfJpaController();
        List<SubjectRf> subjectRfs = controller.findSubjectRfEntities();
        Collections.sort(subjectRfs, new Comparator<SubjectRf>() {

            @Override
            public int compare(SubjectRf t, SubjectRf t1) {
                return t.getName1().compareToIgnoreCase(t1.getName1());
            }
        });
        subjectsLoaded = false;
        for (int i = 0; i < subjectRfs.size(); i++) {
            SubjectRf subjectRf = subjectRfs.get(i);
            jComboBox1.addItem(subjectRf.getName1());
        }
        jComboBox1.setSelectedIndex(-1);
        subjectsLoaded = Boolean.TRUE;
        jXTable1.setColumnControlVisible(true);
        jXTable1.addMouseListener(new PopupListener());
        subjectsLoaded = true;
        jRadioButton2.setText(dzjc.findDicZon(1).getStatusZon());
        jRadioButton3.setText(dzjc.findDicZon(2).getStatusZon());
        jRadioButton4.setText(dzjc.findDicZon(3).getStatusZon());
        jRadioButton5.setText(dzjc.findDicZon(4).getStatusZon());
        this.setExtendedState(Frame.MAXIMIZED_BOTH);

        jButton2.doClick();
    }

    private void filterGeoobjects() {
        if (jComboBox3.getSelectedIndex() > -1) {
            currentGeoobjects = naming == Naming.NEW ? new ArrayList<Geoobject>(currentGSPos.getGeoobjectSet()) : new ArrayList<Geoobject>(currentSelsovet.getGeoobjectSet());
        } else if (jComboBox2.getSelectedIndex() > -1) {
            currentGeoobjects = naming == Naming.NEW ? new ArrayList<Geoobject>(currentRajon.getGeoobjectSet()) : new ArrayList<Geoobject>(currentRajonOld.getGeoobjectSet());
        } else if (jComboBox1.getSelectedIndex() > -1) {
            currentGeoobjects = new ArrayList<Geoobject>(currentSubjectRf.getGeoobjectSet());
        } else {
            currentGeoobjects = new ArrayList<Geoobject>(new GeoobjectJpaController().findGeoobjectEntities());
            SubjectRfJpaController srjc = new SubjectRfJpaController();

        }
        if (!jTextField1.getText().equalsIgnoreCase("") && !jTextField1.getText().equalsIgnoreCase("Название (или его первые символы)")) {
            ArrayList<Geoobject> geoobjects = new ArrayList<Geoobject>();
            for (Geoobject geoobject : currentGeoobjects) {
                if (geoobject.getNameNp().toLowerCase().startsWith(jTextField1.getText().toLowerCase())) {
                    geoobjects.add(geoobject);
                }
            }
            currentGeoobjects = geoobjects;
        }
        if (!jCheckBox1.isSelected()) {
            ArrayList<Geoobject> geoobjects = new ArrayList<Geoobject>();
            for (Geoobject geoobject : currentGeoobjects) {
                if (geoobject.getTipNp() != null && !geoobject.getTipNp().equals("")) {
                    geoobjects.add(geoobject);
                }
            }
            currentGeoobjects = geoobjects;
        }

        if (jCheckBox2.isSelected()) {
            JRadioButton jRadioButton = null;
            JRadioButton[] buttons = new JRadioButton[5];
            buttons[0] = jRadioButton1;
            buttons[1] = jRadioButton2;
            buttons[2] = jRadioButton3;
            buttons[3] = jRadioButton4;
            buttons[4] = jRadioButton5;
            for (int i = 0; i < buttons.length; i++) {
                JRadioButton jRadioButton111 = buttons[i];
                if (jRadioButton111.isSelected()) {
                    jRadioButton = jRadioButton111;
                    break;
                }
            }
            ArrayList<Geoobject> geoobjects = new ArrayList<Geoobject>();
            Integer id = Integer.parseInt(jRadioButton.getAccessibleContext().getAccessibleDescription());
            switch (id) {
                case 1: {
                    for (int j = 0; j < currentGeoobjects.size(); j++) {
                        Geoobject geoobject = currentGeoobjects.get(j);
                        if (geoobject.getCrossZonSet() != null) {
                            ArrayList<CrossZon> crossZons = new ArrayList<CrossZon>(geoobject.getCrossZonSet());
                            for (int k = 0; k < crossZons.size(); k++) {
                                CrossZon crossZon = crossZons.get(k);
                                if (crossZon.getActualZon()) {
                                    geoobjects.add(geoobject);
                                    break;
                                }
                            }
                        }
                    }
                }
                default: {
                    for (Geoobject geoobject : currentGeoobjects) {
                        if (geoobject.getCrossZonSet() != null) {
                            ArrayList<CrossZon> crossZons = new ArrayList<CrossZon>(geoobject.getCrossZonSet());
                            for (CrossZon crossZon : crossZons) {
                                if (crossZon.getDateZonn() == null) {
                                    if (crossZon.getDicZon().getIdZon() == id - 1) {
                                        geoobjects.add(geoobject);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            currentGeoobjects = geoobjects;


        }
    }

    // <editor-fold defaultstate="collapsed" desc="popupListener">
    private class PopupListener extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent me) {

            GeoobjectJpaController gjc = new GeoobjectJpaController();
            if (me.getButton() == MouseEvent.BUTTON1) {
                if (me.getComponent() instanceof JXTable) {
                    JXTable jXTable = (JXTable) me.getComponent();
                    int row = jXTable.rowAtPoint(me.getPoint());
                    //int col = jXTable.columnAtPoint(me.getPoint());
                    jXTable.getColumnExt("Служебная информация").setVisible(true);
                    final Integer geoobjId = (Integer) jXTable.getValueAt(row, jXTable.getColumnExt("Служебная информация").getModelIndex());
                    jXTable.getColumnExt("Служебная информация").setVisible(false);
                    Geoobject g = gjc.findGeoobject(geoobjId);
                    String name = g.getNameNp();
                    String rajon = "";
                    String gspos = "";
                    if (naming == Naming.NEW) {
                        if (g.getRajon() != null) {
                            rajon = g.getRajon().getName2();
                        }
                        if (g.getGSPos() != null) {
                            gspos = g.getGSPos().getName2();
                        }
                    } else {
                        if (g.getRajonOld() != null) {
                            rajon = g.getRajonOld().getPlacename();
                        }
                        if (g.getSelsovet() != null) {
                            gspos = g.getSelsovet().getPlacename();
                        }
                    }
                    String subject = g.getSubjectRf().getName1();
                    String labelText = name + ", ";
                    labelText += gspos.equals("") ? "" : gspos + ", ";
                    labelText += rajon.equals("") ? "" : rajon + ", ";
                    labelText += subject;
                    jXLabel1.setText(labelText);
                }
            } else {
                maybeShowPopup(me);
            }
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            maybeShowPopup(me);
        }

        private void maybeShowPopup(final MouseEvent me) {
            if (me.isPopupTrigger()) {
                if (me.getComponent() instanceof JTable) {
                    final JXTable jTable = (JXTable) me.getComponent();
                    int row = jTable.rowAtPoint(me.getPoint());
                    int col = jTable.columnAtPoint(me.getPoint());
                    if (col == 0) {
                        final JPopupMenu popupMenu = new JPopupMenu();
                        JMenuItem item = new JMenuItem((String) jTable.getValueAt(row, col));
                        jTable.getColumnExt("Служебная информация").setVisible(true);
                        final Integer geoobjId = (Integer) jTable.getValueAt(row, jTable.getColumnExt("Служебная информация").getModelIndex());
                        jTable.getColumnExt("Служебная информация").setVisible(false);
                        item.addActionListener(new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                for (int i = 0; i < currentGeoobjects.size(); i++) {
                                    Geoobject geoobject = currentGeoobjects.get(i);
                                    if (geoobject.getIdNp() == geoobjId) {
                                        System.out.println("Выводится информация по пункту \"" + geoobject.getNameNp() + "\" c id " + geoobject.getIdNp());
                                        ObjInfo info = new ObjInfo(MainForm.this, true);
                                        info.setGeoobjId(geoobjId);
                                        info.setTitle("Информация по населенному пункту " + geoobject.getNameNp());
                                        info.setVisible(true);
                                        break;
                                    }
                                }
                            }
                        });
                        JMenuItem item1 = new JMenuItem("Отмена");
                        item1.addActionListener(new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                popupMenu.setVisible(false);
                            }
                        });
                        popupMenu.add(item);
                        popupMenu.add(item1);
                        popupMenu.show(jTable, me.getX(), me.getY());
                    }
                }
            }
        }
    }// </editor-fold>
    private boolean subjectsLoaded = false;
    private boolean rajonsLoaded = false;
    private SubjectRf currentSubjectRf = null;
    private boolean poselensLoaded = false;
    private Rajon currentRajon;
    private RajonOld currentRajonOld;
    private Selsovet currentSelsovet;
    private GSPos currentGSPos;
    private ArrayList<PokazatelMap> pokazatelMaps = new ArrayList<PokazatelMap>();
    private ArrayList<Geoobject> currentGeoobjects = null;
    private DicZonJpaController dzjc = new DicZonJpaController();

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jComboBox1 = new javax.swing.JComboBox();
        jComboBox2 = new javax.swing.JComboBox();
        jComboBox3 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jXTable1 = new org.jdesktop.swingx.JXTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jXStatusBar1 = new org.jdesktop.swingx.JXStatusBar();
        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jTextField1 = new javax.swing.JTextField();
        jCheckBox1 = new javax.swing.JCheckBox();
        jXCollapsiblePane1 = new org.jdesktop.swingx.JXCollapsiblePane();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        jRadioButton5 = new javax.swing.JRadioButton();
        jCheckBox2 = new javax.swing.JCheckBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
        jRadioButtonMenuItem2 = new javax.swing.JRadioButtonMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
        jComboBox1.setName("jComboBox1"); // NOI18N
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
        jComboBox2.setName("jComboBox2"); // NOI18N
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
        jComboBox3.setName("jComboBox3"); // NOI18N
        jComboBox3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox3ActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jXTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ) {
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        });
        jXTable1.setName("jXTable1"); // NOI18N
        jScrollPane1.setViewportView(jXTable1);

        jButton1.setText("Показать");
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Сбросить");
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jXStatusBar1.setName("jXStatusBar1"); // NOI18N

        jXLabel1.setName("jXLabel1"); // NOI18N
        jXStatusBar1.add(jXLabel1);

        jTextField1.setForeground(new java.awt.Color(142, 142, 142));
        jTextField1.setText("Название (или его первые символы)");
        jTextField1.setName("jTextField1"); // NOI18N
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField1FocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField1FocusLost(evt);
            }
        });

        jCheckBox1.setText("Отображать упраздненные населенные пункты");
        jCheckBox1.setName("jCheckBox1"); // NOI18N

        jXCollapsiblePane1.setCollapsed(true);
        jXCollapsiblePane1.setName("jXCollapsiblePane1"); // NOI18N

        buttonGroup2.add(jRadioButton1);
        jRadioButton1.setSelected(true);
        jRadioButton1.setText("Любая");
        jRadioButton1.setName("jRadioButton1"); // NOI18N
        jXCollapsiblePane1.getContentPane().add(jRadioButton1);
        jRadioButton1.getAccessibleContext().setAccessibleDescription("1");

        buttonGroup2.add(jRadioButton2);
        jRadioButton2.setName("jRadioButton2"); // NOI18N
        jXCollapsiblePane1.getContentPane().add(jRadioButton2);
        jRadioButton2.getAccessibleContext().setAccessibleDescription("2");

        buttonGroup2.add(jRadioButton3);
        jRadioButton3.setName("jRadioButton3"); // NOI18N
        jXCollapsiblePane1.getContentPane().add(jRadioButton3);
        jRadioButton3.getAccessibleContext().setAccessibleDescription("3");

        buttonGroup2.add(jRadioButton4);
        jRadioButton4.setName("jRadioButton4"); // NOI18N
        jXCollapsiblePane1.getContentPane().add(jRadioButton4);
        jRadioButton4.getAccessibleContext().setAccessibleDescription("4");

        buttonGroup2.add(jRadioButton5);
        jRadioButton5.setName("jRadioButton5"); // NOI18N
        jXCollapsiblePane1.getContentPane().add(jRadioButton5);
        jRadioButton5.getAccessibleContext().setAccessibleDescription("5");

        jCheckBox2.setText("Фильтровать по зоне");
        jCheckBox2.setName("jCheckBox2"); // NOI18N
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        jMenu1.setText("Файл");
        jMenu1.setName("jMenu1"); // NOI18N

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Выход");
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Опции");
        jMenu2.setName("jMenu2"); // NOI18N

        jMenuItem2.setText("Показатели");
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jMenu2.add(jSeparator1);

        buttonGroup1.add(jRadioButtonMenuItem1);
        jRadioButtonMenuItem1.setSelected(true);
        jRadioButtonMenuItem1.setText("Новое именование районов");
        jRadioButtonMenuItem1.setName("jRadioButtonMenuItem1"); // NOI18N
        jRadioButtonMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jRadioButtonMenuItem1);

        buttonGroup1.add(jRadioButtonMenuItem2);
        jRadioButtonMenuItem2.setText("Старое именование");
        jRadioButtonMenuItem2.setName("jRadioButtonMenuItem2"); // NOI18N
        jRadioButtonMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jRadioButtonMenuItem2);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Аналитический блок");
        jMenu3.setName("jMenu3"); // NOI18N

        jMenuItem3.setText("Список объектов, находящихся в зоне радиоактивного загрязнения");
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem3);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jXCollapsiblePane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jCheckBox1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
                    .add(jCheckBox2))
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 699, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jComboBox1, 0, 221, Short.MAX_VALUE)
                        .add(18, 18, 18)
                        .add(jComboBox2, 0, 221, Short.MAX_VALUE)
                        .add(18, 18, 18)
                        .add(jComboBox3, 0, 221, Short.MAX_VALUE)))
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jXStatusBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 723, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jComboBox3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jCheckBox1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jCheckBox2))
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jXCollapsiblePane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton2)
                    .add(jButton1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1651, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jXStatusBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
        if (subjectsLoaded) {
            rajonsLoaded = false;
            poselensLoaded = false;
            jComboBox3.removeAllItems();
            jComboBox2.removeAllItems();
            SubjectRfJpaController controller = new SubjectRfJpaController();
            String subjectName = jComboBox1.getSelectedItem().toString();
            for (SubjectRf subjectRf : controller.findSubjectRfEntities()) {
                if (subjectRf.getName1().equalsIgnoreCase(subjectName)) {
                    currentSubjectRf = subjectRf;
                    break;
                }
            }
            if (this.naming == Naming.NEW) {
                List<Rajon> rajons = new ArrayList<Rajon>(currentSubjectRf.getRajonSet());
                Collections.sort(rajons, new Comparator<Rajon>() {

                    @Override
                    public int compare(Rajon t, Rajon t1) {
                        return t.getNumberPp().compareToIgnoreCase(t1.getNumberPp());
                    }
                });
                for (int i = 0; i < rajons.size(); i++) {
                    Rajon rajon = rajons.get(i);
                    if (rajon.getSubjectRf().equals(currentSubjectRf)) {
                        jComboBox2.addItem(rajon.getName2());
                    }
                }
            } else {
                List<RajonOld> rajonOlds = new ArrayList<RajonOld>(currentSubjectRf.getRajonOldSet());
                Collections.sort(rajonOlds, new Comparator<RajonOld>() {

                    @Override
                    public int compare(RajonOld o1, RajonOld o2) {
                        return o1.getPlacename().compareToIgnoreCase(o2.getPlacename());
                    }
                });
                for (RajonOld rajonOld : rajonOlds) {
                    jComboBox2.addItem(rajonOld.getPlacename());
                }
            }
            currentRajon = null;
            currentGSPos = null;
            jComboBox2.setSelectedIndex(-1);
            jComboBox3.setSelectedIndex(-1);
            rajonsLoaded = true;

        }
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        if (rajonsLoaded) {
            poselensLoaded = false;
            jComboBox3.removeAllItems();
            if (naming == Naming.NEW) {
                ArrayList<Rajon> rajons = new ArrayList<Rajon>(currentSubjectRf.getRajonSet());
                for (int i = 0; i < rajons.size(); i++) {
                    Rajon rajon = rajons.get(i);
                    if (rajon.getName2().equalsIgnoreCase(jComboBox2.getSelectedItem().toString())) {
                        currentRajon = rajon;
                        break;
                    }

                }
                ArrayList<GSPos> gSPoses = new ArrayList<GSPos>(currentRajon.getGSPosSet());
                Collections.sort(gSPoses, new Comparator<GSPos>() {

                    @Override
                    public int compare(GSPos t, GSPos t1) {
                        return t.getNumberPp().compareToIgnoreCase(t1.getNumberPp());
                    }
                });
                for (GSPos gSPos : gSPoses) {
                    jComboBox3.addItem(gSPos.getName2());
                }
            } else {
                ArrayList<RajonOld> rajonOlds = new ArrayList<RajonOld>(currentSubjectRf.getRajonOldSet());
                for (RajonOld rajonOld : rajonOlds) {
                    if (rajonOld.getPlacename().equalsIgnoreCase(jComboBox2.getSelectedItem().toString())) {
                        currentRajonOld = rajonOld;
                        break;
                    }
                }
                ArrayList<Selsovet> selsovets = new ArrayList<Selsovet>(currentRajonOld.getSelsovetSet());
                Collections.sort(selsovets, new Comparator<Selsovet>() {

                    @Override
                    public int compare(Selsovet o1, Selsovet o2) {
                        return o1.getNumberPp().compareToIgnoreCase(o2.getNumberPp());
                    }
                });
                for (Selsovet selsovet : selsovets) {
                    jComboBox3.addItem(selsovet.getPlacename());
                }
            }

            jComboBox3.setSelectedIndex(-1);
            poselensLoaded = true;
        }
    }//GEN-LAST:event_jComboBox2ActionPerformed

    private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed
        if (poselensLoaded) {
            if (naming == Naming.NEW) {
                ArrayList<GSPos> gSPoses = new ArrayList<GSPos>(currentRajon.getGSPosSet());
                for (int i = 0; i < gSPoses.size(); i++) {
                    GSPos gSPos = gSPoses.get(i);
                    if (gSPos.getName2().equalsIgnoreCase(jComboBox3.getSelectedItem().toString())) {
                        currentGSPos = gSPos;
                        break;
                    }
                }
            } else {
                ArrayList<Selsovet> selsovets = new ArrayList<Selsovet>(currentRajonOld.getSelsovetSet());
                for (Selsovet selsovet : selsovets) {
                    if (selsovet.getPlacename().equalsIgnoreCase(jComboBox3.getSelectedItem().toString())) {
                        currentSelsovet = selsovet;
                        break;
                    }
                }
            }
        }
    }//GEN-LAST:event_jComboBox3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        final Loading wait = new Loading(this, false);
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                wait.repaint();
                ResultJpaController rjc = new ResultJpaController();
                Object[][] table;
                Object[] titles;
                filterGeoobjects();
                if (!currentGeoobjects.isEmpty()) {
                    table = new Object[currentGeoobjects.size()][pokazatelMaps.size() + 2];
                    for (int i = 0; i < currentGeoobjects.size(); i++) {
                        Geoobject geoobject = currentGeoobjects.get(i);
                        wait.setText(geoobject.getNameNp());
                        wait.repaint(1);
                        for (int j = 0; j < pokazatelMaps.size(); j++) {
                            PokazatelMap pokazatelMap = pokazatelMaps.get(j);
                            String res = rjc.getResByIdPIdGeoobjeIdTime(pokazatelMap.getPokazatel().getIdP(), geoobject.getIdNp(), pokazatelMap.getTime().getIdTime());
                            table[i][j + 2] = res;
                            table[i][0] = geoobject.getTipNp().equals("") ? geoobject.getNameNp() : geoobject.getTipNp() + ". " + geoobject.getNameNp();
                            table[i][1] = geoobject.getIdNp();
                        }
                    }
                    titles = new Object[pokazatelMaps.size() + 2];
                    for (int i = 0; i < pokazatelMaps.size(); i++) {
                        PokazatelMap pokazatelMap = pokazatelMaps.get(i);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy г.");
                        titles[i + 2] = "<html>" + pokazatelMap.getPokazatel().getShortPok() + "<br>" + sdf.format(pokazatelMap.getTime().getTN()) + "</html>";
                    }
                    titles[0] = "Название населенного пункта";
                    titles[1] = "Служебная информация";
                    jXTable1.setModel(new DefaultTableModel(table, titles));
                    TableColumnExt tce = jXTable1.getColumnExt(1);
                    tce.setVisible(false);
                    tce.setResizable(false);
                    tce.setMaxWidth(-1);

                } else {
                    JOptionPane.showMessageDialog(null, new Label("Нет населенных пунктов"));
                }
                jXTable1.packAll();
                wait.close();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jRadioButtonMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItem1ActionPerformed
        if (jRadioButtonMenuItem1.isSelected()) {
            naming = Naming.NEW;
        } else {
            naming = Naming.OLD;
        }
    }//GEN-LAST:event_jRadioButtonMenuItem1ActionPerformed

    private void jRadioButtonMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItem2ActionPerformed
        if (jRadioButtonMenuItem1.isSelected()) {
            this.naming = Naming.NEW;
        } else {
            this.naming = Naming.OLD;
        }
        rajonsLoaded = false;
        poselensLoaded = false;
        jComboBox1.setSelectedIndex(jComboBox1.getSelectedIndex());
    }//GEN-LAST:event_jRadioButtonMenuItem2ActionPerformed

    private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained
        if (jTextField1.getText().equalsIgnoreCase("Название (или его первые символы)")) {
            jTextField1.setText("");
            jTextField1.setForeground(new Color(1, 1, 1));
        }
    }//GEN-LAST:event_jTextField1FocusGained

    private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
        if (jTextField1.getText().equals("")) {
            jTextField1.setText("Название (или его первые символы)");
            jTextField1.setForeground(new Color(142, 142, 142));
        }
    }//GEN-LAST:event_jTextField1FocusLost

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        jXCollapsiblePane1.setCollapsed(!jCheckBox2.isSelected());
    }//GEN-LAST:event_jCheckBox2ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        OptionsDialog dialog = new OptionsDialog(this, true);
        dialog.setVisible(true);
        preloadPokazatelMaps(new File("conf/config.xml"));
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        AnalysisDialog r = new AnalysisDialog();
        r.setVisible(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        SwingUtilities.invokeLater(new Thread(new Runnable() {

            @Override
            public void run() {
                Settings s = new Settings();
                jComboBox1.setSelectedIndex(s.getSubjectPosition());
                jCheckBox1.setEnabled(s.getWithNonExistent());
                jButton1.doClick();
            }
        }, "some"));
    }//GEN-LAST:event_jButton2ActionPerformed

    public static void main(final String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainForm(getConfigFile()).setVisible(true);
            }

            private File getConfigFile() {
                return (args == null || args.length == 0 || args[0].equals("")) ? new File("conf/config.xml") : new File(args[0]);
            }
        });

    }
    // <editor-fold defaultstate="collapsed" desc="Generated variables">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.ButtonGroup buttonGroup1;
    public javax.swing.ButtonGroup buttonGroup2;
    public javax.swing.JButton jButton1;
    public javax.swing.JButton jButton2;
    public javax.swing.JCheckBox jCheckBox1;
    public javax.swing.JCheckBox jCheckBox2;
    public javax.swing.JComboBox jComboBox1;
    public javax.swing.JComboBox jComboBox2;
    public javax.swing.JComboBox jComboBox3;
    public javax.swing.JMenu jMenu1;
    public javax.swing.JMenu jMenu2;
    public javax.swing.JMenu jMenu3;
    public javax.swing.JMenuBar jMenuBar1;
    public javax.swing.JMenuItem jMenuItem1;
    public javax.swing.JMenuItem jMenuItem2;
    public javax.swing.JMenuItem jMenuItem3;
    public javax.swing.JPopupMenu jPopupMenu1;
    public javax.swing.JRadioButton jRadioButton1;
    public javax.swing.JRadioButton jRadioButton2;
    public javax.swing.JRadioButton jRadioButton3;
    public javax.swing.JRadioButton jRadioButton4;
    public javax.swing.JRadioButton jRadioButton5;
    public javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
    public javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem2;
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JPopupMenu.Separator jSeparator1;
    public javax.swing.JTextField jTextField1;
    public org.jdesktop.swingx.JXCollapsiblePane jXCollapsiblePane1;
    public org.jdesktop.swingx.JXLabel jXLabel1;
    public org.jdesktop.swingx.JXStatusBar jXStatusBar1;
    public org.jdesktop.swingx.JXTable jXTable1;
    // End of variables declaration//GEN-END:variables
// </editor-fold>

    public void preloadPokazatelMaps(File configFile) {
        if (configFile != null) {
            Properties config = new Properties();
            try {
                config.loadFromXML(new FileInputStream(configFile));
            } catch (IOException ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
            String pokazateli = config.getProperty("pokazateli");
            String[] neededPokazatels = pokazateli.split(";");
            ResultJpaController rjc = new ResultJpaController();
            PokazatelJpaController pjc = new PokazatelJpaController();
            DicTimeJpaController dtjc = new DicTimeJpaController();
            String me;
            for (int i = 0; i < neededPokazatels.length; i++) {
                String string = neededPokazatels[i];
                me = string;
                Integer dicTimeId = rjc.getMaxDicTimeByIdP(Integer.parseInt(string));
                try {
                    pokazatelMaps.add(new PokazatelMap(pjc.findPokazatel(Integer.parseInt(string)), dtjc.findDicTime(dicTimeId)));
                } catch (Exception e) {
                    System.err.println(me);
                }
            }
        } else {
            Properties config = new Properties();
            try {
                config.loadFromXML(new FileInputStream(new File("./conf/config.xml")));
            } catch (IOException ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
            String pokazateli = config.getProperty("pokazateli");
            String[] neededPokazatels = pokazateli.split(";");
            ResultJpaController rjc = new ResultJpaController();
            PokazatelJpaController pjc = new PokazatelJpaController();
            DicTimeJpaController dtjc = new DicTimeJpaController();
            for (int i = 0; i < neededPokazatels.length; i++) {
                String string = neededPokazatels[i];
                Integer dicTimeId = rjc.getMaxDicTimeByIdP(Integer.parseInt(string));
                pokazatelMaps.add(new PokazatelMap(pjc.findPokazatel(Integer.parseInt(string)), dtjc.findDicTime(dicTimeId)));
            }
        }
    }

    private final class ProgressBarProgresser implements Runnable {

        private JProgressBar progressBar;
        private Integer value;

        public ProgressBarProgresser(JProgressBar progressBar) {
            this.progressBar = progressBar;
        }

        @Override
        public void run() {
            progressBar.setValue(progressBar.getValue() + 1);
        }
    }
}
